package com.linkage.seapeak.activity.vote;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Project.CreateProTalkActivity;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.seapeak.activity.message.MultiSendActivity;
import com.linkage.seapeak.activity.message.ScreenUserActivity;
import com.linkage.seapeak.activity.message.ScreenVoteUserActivity;
import com.linkage.seapeak.adapter.CrediterAdapter;
import com.linkage.seapeak.base.BaseWhiteActivity;
import com.linkage.seapeak.net.ResultCallBack;
import com.linkage.seapeak.net.VoteNetRequest;
import com.linkage.seapeak.pojo.CrediterUser;
import com.linkage.seapeak.pojo.VoteGroup;
import com.linkage.seapeak.view.CreditorOrderDialog;
import com.seapeak.recyclebundle.AYSwipeRecyclerView;
import com.seapeak.recyclebundle.BaseRecyclerAdapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 表决成员选择人员
 */
public class VoteMemberMultiSelectActivity extends BaseWhiteActivity implements AYSwipeRecyclerView.OnRefreshLoadListener {

    List<CrediterUser> userList;
    AYSwipeRecyclerView recyclerView;
    CrediterAdapter adapter;

    TextView count_member, order_item, all_select, screen_member;
    TextView menu;
    EditText search_edit;

    String projectId;
    String voteId;
    int voteType;
    int role ;
    String groupId;

    String grouped;
    Integer committee = null;
    Boolean onlineStatus = null;
    Boolean kindTax = null;
    Boolean kindGuarantee = null;
    Boolean kindOther = null;
    Boolean kindOrdinary = null;

    Boolean groupkindGuarantee = null;
    Boolean groupkindOther = null;
    Boolean groupkindOrdinary = null;

    Double minAmountDeclared = null;
    Double maxAmountDeclared = null;
    Double minConfirmAmount = null;
    Double maxConfirmAmount = null;
    String processStatus = null;

    String orderBy = "";
    String orderColumn = "";

    int pageNo = 1;
    int pageSize = 20;

    //已选择人的ids;
    List<String> selectIds;
    List<String> alreadySelectIds;
    int selectType = 1;
    boolean canSelectAlready = true;

    VoteGroup voteGroup = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vote_multi_select, "添加成员");
        init();
    }

    private void init() {
        projectId = getIntent().getStringExtra("projectId");
        voteId = getIntent().getStringExtra("voteId");
        voteType = getIntent().getIntExtra("voteType", -1);
        grouped= getIntent().getStringExtra("grouped");
//        groupId = getIntent().getStringExtra("groupId");
        voteGroup = (VoteGroup) getIntent().getSerializableExtra("voteGroup");
//        债委会筛选时忽略人员类别筛选条件
        if (voteType == 2)
            committee = 2;

        role = -1;
        recyclerView = findViewById(R.id.member_list);
        count_member = findViewById(R.id.count_member);
        all_select = findViewById(R.id.all_select);
        order_item = findViewById(R.id.order_item);
        screen_member = findViewById(R.id.screen_member);
        search_edit = findViewById(R.id.search_edit);

        if (voteGroup != null) {
            groupkindOrdinary = voteGroup.isOrdinary();
            groupkindGuarantee = voteGroup.isGuarantee();
            groupkindOther = voteGroup.isOther();
            groupId =voteGroup.getId();
            screen_member.setVisibility(View.GONE);
            grouped = "1";
        }

        canSelectAlready = getIntent().getBooleanExtra("canSelectAlready", true);
        alreadySelectIds = getIntent().getStringArrayListExtra("alreadySelectIds");
        if (alreadySelectIds == null)
            alreadySelectIds = new ArrayList<>();
        selectIds = new ArrayList<>();
//        selectIds.addAll(alreadySelectIds);



        userList = new ArrayList<>();
        recyclerView.setOnRefreshLoadLister(this);
        recyclerView.setMode(AYSwipeRecyclerView.SwipeType.ONLY_START);
        adapter = new CrediterAdapter(VoteMemberMultiSelectActivity.this, userList, true);
        recyclerView.setAdapter(adapter);
        recyclerView.startLoadFirst();
        recyclerView.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position, RecyclerView.ViewHolder viewHolder) {
                if (!canSelectAlready && alreadySelectIds.contains(userList.get(position).getCreditorid()))
                    return;

                boolean itemCheck = userList.get(position).isCheck;
                userList.get(position).isCheck = !itemCheck;
                if (selectType == 3) {
                    if (!itemCheck)
                        selectIds.add(userList.get(position).getCreditorid());
                    else
                        selectIds.remove(userList.get(position).getCreditorid());
                } else {
                    if (itemCheck)
                        selectIds.add(userList.get(position).getCreditorid());
                    else
                        selectIds.remove(userList.get(position).getCreditorid());
                }
                adapter.notifyDataSetChanged();
//                menu.setText("完成(" + selectIds.size() + ")");
//                menu.setText("完成");
            }
        });

        search_edit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    loadFirst();
                    return false;
                } else
                    return true;
            }
        });

        all_select.setText(selectType == 3 ? "全选" : "取消");
        all_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adapter.setAllSelect(selectType == 3);
                selectType = selectType == 3 ? 1 : 3;
                all_select.setText(selectType == 3 ? "全选" : "取消");
                selectIds.clear();
//                menu.setText("完成(" + selectIds.size() + ")");
                adapter.notifyDataSetChanged();
            }
        });

        order_item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final CreditorOrderDialog dialog = new CreditorOrderDialog(VoteMemberMultiSelectActivity.this);
                dialog.init(VoteMemberMultiSelectActivity.this, orderColumn, orderBy);
                dialog.setSureListener(new CreditorOrderDialog.OnSureListener() {
                    @Override
                    public void onSure(int orderType, int orderOrien) {
//                        declareTime 申报时间
//                        confirmTime 确认时间
//                        amountDeclared 申报金额
//                        confirmAmount 确认金额
                        if (orderType == 1)
                            orderColumn = "confirmAmount";
                        else if (orderType == 2)
                            orderColumn = "amountDeclared";
                        else if (orderType == 3)
                            orderColumn = "confirmTime";
                        else if (orderType == 4)
                            orderColumn = "declareTime";
                        orderBy = orderOrien == 2 ? "asc" : "desc";
                        getCreditorList(true);
                        dialog.dismiss();
                    }
                });
                dialog.show();
            }
        });

        screen_member.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(VoteMemberMultiSelectActivity.this, ScreenVoteUserActivity.class);
                intent.putExtra("voteType", voteType);
                if (voteGroup != null)
                    intent.putExtra("voteGroup", voteGroup);
                startActivityForResult(intent, 0x11);
            }
        });

        menu = (TextView) addMenu(new MenuAction(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ((selectIds == null || selectIds.size() == 0) && selectType == 3) {
                    showToast("请至少选择一个成员");
                    return;
                }

                List<CrediterUser> selectList = new ArrayList<>();
                for (int i = 0; i < userList.size(); i++) {
                    CrediterUser user = userList.get(i);
                    if (user != null && ((user.isCheck && selectType == 3) || (!user.isCheck && selectType != 3)) ) {
                        selectList.add(user);
                        if (selectType == 1)
                            selectType = 2;
                    }
                }

//                //                    计算新增的用户
//                List<CrediterUser> appendList = new ArrayList<>();
//                for (CrediterUser user : selectList) {
//                    if (alreadySelectIds.contains(user.getCreditorid()))
//                        continue;
//                    else
//                        appendList.add(user);
//                }
                Intent intent = new Intent();
                intent.putExtra("userList", (Serializable) selectList);
//                intent.putExtra("appendList", (Serializable) appendList);
                intent.putExtra("selectType", selectType);

                HashMap<String, String> parms = new HashMap<>();

                parms.put("userToken", getUserToken());
                parms.put("projectId", projectId);
//                parms.put("pageNumber", pageNo + "");
                parms.put("voteId", voteId);
                parms.put("voteType", voteType + "");
//                parms.put("pageSize", pageSize + "");
                parms.put("creditorName", search_edit.getText().toString());

//        parms.put("groupId",   groupId);
                if(groupId!=null && !"".equalsIgnoreCase(groupId))
                {
                    parms.put("groupId",   groupId);
                }
                parms.put("grouped",   grouped);

//                if(role!=-1)  parms.put("role", role + "");

                if (committee != null) parms.put("committee", committee + "");
                if (onlineStatus != null) parms.put("onlineStatus", onlineStatus + "");

                if (kindTax != null) parms.put("kindTax", kindTax + "");
                if (kindGuarantee != null) parms.put("KindGuarantee", kindGuarantee + "");
                if (kindOther != null) parms.put("KindOther", kindOther + "");
                if (kindOrdinary != null) parms.put("kindOrdinary", kindOrdinary + "");

                if (groupkindOrdinary != null) parms.put("groupKindOrdinary", groupkindOrdinary + "");

                if (groupkindOrdinary!=null && groupkindOrdinary) {
                    parms.put("kindTax", "1");
                    parms.put("kindOrdinary", "1");
                }
                if (groupkindOther!=null && groupkindOther) {
                    parms.put("kindOther", "1");
                }

                if (groupkindGuarantee!=null && groupkindGuarantee) {
                    parms.put("kindGuarantee", "1");
                }


                if (groupkindGuarantee != null) parms.put("groupKindGuarantee", groupkindGuarantee + "");
                if (groupkindOther != null) parms.put("groupKindOther", groupkindOther + "");
                if (groupkindOrdinary != null) parms.put("groupKindOrdinary", groupkindOrdinary + "");

                if (minAmountDeclared != null && minAmountDeclared != 0f) parms.put("minAmountDeclared", minAmountDeclared + "");
                if (maxAmountDeclared != null && maxAmountDeclared != 0f) parms.put("maxAmountDeclared", maxAmountDeclared + "");
                if (minConfirmAmount != null && minConfirmAmount != 0f) parms.put("minConfirmAmount", minConfirmAmount + "");
                if (maxConfirmAmount != null && maxConfirmAmount != 0f) parms.put("maxConfirmAmount", maxConfirmAmount + "");
                if (processStatus != null) parms.put("processStatus", processStatus + "");
//                if (!TextUtils.isEmpty(orderBy)) parms.put("orderBy", orderBy + "");
//                if (!TextUtils.isEmpty(orderColumn)) parms.put("orderColumn", orderColumn + "");

//                if (committee != null) parms.put("committee", committee + "");
//                if (onlineStatus != null) parms.put("onlineStatus", onlineStatus + "");
//                if (kindTax != null) parms.put("kindTax", kindTax + "");
//                if (kindGuarantee != null) parms.put("kindGuarantee", kindGuarantee + "");
//                if (kindOther != null) parms.put("kindOther", kindOther + "");
//                if (kindOrdinary != null) parms.put("kindOrdinary", kindOrdinary + "");
//                if (minAmountDeclared != null && minAmountDeclared != 0f) parms.put("minAmountDeclared", minAmountDeclared + "");
//                if (maxAmountDeclared != null && maxAmountDeclared != 0f) parms.put("maxAmountDeclared", maxAmountDeclared + "");
//                if (minConfirmAmount != null && minConfirmAmount != 0f) parms.put("minConfirmAmount", minConfirmAmount + "");
//                if (maxConfirmAmount != null && maxConfirmAmount != 0f) parms.put("maxConfirmAmount", maxConfirmAmount + "");
//                if (processStatus != null) parms.put("processStatus", processStatus + "");
//                parms.put("creditorName", search_edit.getText().toString() + "");
                addVoteMember(parms,selectList,selectType);
//                intent.putExtra("parms", parms);
//
//                setResult(RESULT_OK, intent);
//                finish();
            }
        }, "完成", 0));
    }

    /**
     * 添加人员
     * @param userList
     */
    private void addVoteMember(HashMap<String, String> parms, final List<CrediterUser> userList, int type) {
//        showProgress();
        VoteNetRequest.addVoteMember(getUserToken(), parms, type, voteId, projectId,  userList, new ResultCallBack<String>() {
            @Override
            public void onSuccess(String result) {
//                hideProgress();
//                finish();
                Intent intent = new Intent();
                setResult(RESULT_OK, intent);
                finish();
//                loadFirst();
            }

            @Override
            public void onFailed(String msg) {
//                hideProgress();
                showToast(msg);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x11 && resultCode == RESULT_OK && data != null) {
             committee = data.getIntExtra("committee", 1);
             int online = data.getIntExtra("onlineStatus", 0);
             if (online == 0)
                 onlineStatus = null;
             else if (online == 1)
                 onlineStatus = true;
             else
                 onlineStatus = false;
             kindTax = data.getBooleanExtra("kindTax", false);
             kindGuarantee = data.getBooleanExtra("kindGuarantee", false);
             kindOther = data.getBooleanExtra("kindOther", false);
             kindOrdinary = data.getBooleanExtra("kindOrdinary", false);
             minAmountDeclared = data.getDoubleExtra("minAmountDeclared", 0);
             maxAmountDeclared = data.getDoubleExtra("maxAmountDeclared", 0);
             minConfirmAmount = data.getDoubleExtra("minConfirmAmount", 0);
             maxConfirmAmount = data.getDoubleExtra("maxConfirmAmount", 0);
             processStatus = data.getStringExtra("processStatus");
             loadFirst();
        }
    }

    @Override
    public void loadFirst() {
        pageNo = 1;
        getCreditorList(true);
    }

    @Override
    public void loadNext() {
        getCreditorList(false);
    }

    /**
     * 获取成员
     */
    public void getCreditorList(final boolean isFirst) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            getToken(null);
            return;
        }

        LinkedHashMap<String, String> parms = new LinkedHashMap<>();
        parms.put("userToken", getUserToken());
        parms.put("projectId", projectId);
        parms.put("pageNumber", pageNo + "");
        parms.put("voteId", voteId);
        parms.put("voteType", voteType + "");
        parms.put("pageSize", pageSize + "");
        parms.put("creditorName", search_edit.getText().toString());

//        parms.put("groupId",   groupId);
        if(groupId!=null && !"".equalsIgnoreCase(groupId)) {
            parms.put("groupId",   groupId);
        }
        parms.put("grouped", grouped);

        if(role!=-1)  parms.put("role", role + "");

        if (committee != null) parms.put("role", committee + "");
        if (onlineStatus != null) parms.put("onlineStatus", onlineStatus + "");

        if (kindTax != null) parms.put("kindTax", kindTax + "");
        if (kindGuarantee != null) parms.put("kindGuarantee", kindGuarantee + "");
        if (kindOther != null) parms.put("kindOther", kindOther + "");
        if (kindOther != null) parms.put("kindOrdinary", kindOrdinary + "");

        if (groupkindOrdinary != null) parms.put("groupKindOrdinary", groupkindOrdinary + "");
        if (groupkindGuarantee != null) parms.put("groupKindGuarantee", groupkindGuarantee + "");
        if (groupkindOther != null) parms.put("groupKindOther", groupkindOther + "");
        if (groupkindOrdinary != null) parms.put("groupKindOrdinary", groupkindOrdinary + "");

        if (groupkindOrdinary != null) parms.put("groupKindOrdinary", groupkindOrdinary + "");

        if (groupkindOrdinary!=null && groupkindOrdinary) {
            parms.put("kindTax", "1");
            parms.put("kindOrdinary", "1");
        }
        if (groupkindOther!=null && groupkindOther) {
            parms.put("kindOther", "1");
        }

        if (groupkindGuarantee!=null && groupkindGuarantee) {
            parms.put("kindGuarantee", "1");
        }


        if (minAmountDeclared != null && minAmountDeclared != 0f) parms.put("minAmountDeclared", minAmountDeclared + "");
        if (maxAmountDeclared != null && maxAmountDeclared != 0f) parms.put("maxAmountDeclared", maxAmountDeclared + "");
        if (minConfirmAmount != null && minConfirmAmount != 0f) parms.put("minConfirmAmount", minConfirmAmount + "");
        if (maxConfirmAmount != null && maxConfirmAmount != 0f) parms.put("maxConfirmAmount", maxConfirmAmount + "");
        if (processStatus != null) parms.put("processStatus", processStatus + "");
        if (!TextUtils.isEmpty(orderBy)) parms.put("orderBy", orderBy + "");
        if (!TextUtils.isEmpty(orderColumn)) parms.put("orderColumn", orderColumn + "");

        Network.getAPIService()
                .getCreditorList(parms)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onError(new Throwable(json.get("msg").getAsString()));
                            return;
                        } else {
                            if (isFirst) {
                                userList.clear();
                            }

                            JsonObject data = json.getAsJsonObject("data");
                                JsonArray array = data.getAsJsonArray("list");
                            List<CrediterUser> temp = new ArrayList<>();
                            for (int i = 0;i < array.size();i++) {
                                CrediterUser item = new Gson().fromJson(array.get(i), CrediterUser.class);
                                item.setConfirmedMoney(item.getConfirmAmount());
                                if (selectType == 3) {
                                    if (selectIds.contains(item.getCreditorid())) {
                                        item.isCheck = true;
                                    } else
                                        item.isCheck = false;
                                } else {
                                    if (selectIds.contains(item.getCreditorid())) {
                                        item.isCheck = false;
                                    } else
                                        item.isCheck = true;
                                }
                                temp.add(item);
                            }

                            userList.addAll(temp);
                            int count = data.get("totalCount").getAsInt();
                            recyclerView.onFinishRequest(false, pageNo * pageSize < count);
                            pageNo++;
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        recyclerView.onFinishRequest(true, false);
                    }
                });
    }
}
